import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author quan
 * @Description Servlet实现一个计算器:form表单的形式
 * @Date 2023/6/23 15:59
 */
//2、创建路由
@WebServlet("/calculator_form")
//1、创建类，继承HttpServlet
public class Calculator_form extends HttpServlet {
    /**
     * 目标：从前端拿两个参数：num1和num2，进行相加操作并将结果返回给前端
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    //生成doPost或者doGet方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    //重写doPost方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //0、设置返回的数据类型和编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //1、从请求req中获取参数num1
        String num1 = req.getParameter("num1");
        String num2 = req.getParameter("num2");
        //2、参数的合法性校验
        if(num1==null || num1.equals("") || num2==null || num2.equals("")){
            //直接返回错误信息
            resp.getWriter().write("抱歉，参数有误");
            return;
        }
        //3、进行类型转换String-int
        int number1 = Integer.valueOf(num1);
        int number2 = Integer.valueOf(num2);
        //4、计算相加的结果
        int res = number1+number2;
        //5、将计算结果返回给前端
        resp.getWriter().write("相加结果："+res);
    }
}
